package com.lqk.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class ServerDemo {
    public static void main(String[] args) throws Exception {
        // 1 获取服务端通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        // 2 切换非阻塞模式
        serverSocketChannel.configureBlocking(false);

        // 3 创建 Buffer
        ByteBuffer serverByteBuffer = ByteBuffer.allocate(1024);

        // 4 绑定端口号进行监听
        serverSocketChannel.bind(new InetSocketAddress(8080));

        // 5 获取 Selector 选择器
        Selector selector = Selector.open();

        // 6 通道注册到选择器上，进行监听，指定感兴趣的事件是 ACCEPT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // 7 选择器进行轮询，进行后续操作
        while (selector.select()>0){
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            // 遍历
            Iterator<SelectionKey> selectionKeyIterator = selectionKeys.iterator();
            while (selectionKeyIterator.hasNext()){
                // 获取就绪操作
                SelectionKey selectionKey = selectionKeyIterator.next();
                // 判断是什么操作
                if (selectionKey.isAcceptable()){
                    // 获取连接
                    SocketChannel accept = serverSocketChannel.accept();
                    // 切换非阻塞模式
                    accept.configureBlocking(false);
                    // 选择器注册，声明这个channel只对读操作感兴趣
                    accept.register(selector,SelectionKey.OP_READ);

                }else if (selectionKey.isReadable()){
                    SocketChannel channel = (SocketChannel)selectionKey.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    //读取数据
                    int length=0;
                    while ((length=channel.read(byteBuffer))>0){
                        byteBuffer.flip();
                        System.out.println(new String(byteBuffer.array(),0,length));
                        byteBuffer.clear();
                    }

                }
                selectionKeyIterator.remove();
            }

        }
    }
}
